package com.chyblog.demo;

import com.chyblog.demo.clients.DiscoveryClientExample;
import com.chyblog.demo.clients.FeignExample;
import com.chyblog.demo.clients.RestTemplateExample;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.netflix.feign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

@EnableDiscoveryClient
@EnableFeignClients
@SpringBootApplication
public class AppDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(AppDemoApplication.class, args);
    }

    @Bean
    @LoadBalanced
    public RestTemplate restTemplate(RestTemplateBuilder builder) {
        // Do any additional configuration here
        return builder.build();
    }
}

@RefreshScope
@RestController
class ServerRestController {

    @Value("${message:Hello client default}")
    private String message;

    @GetMapping("/message")
    public String getMessage() {
        return this.message;
    }

    @GetMapping("/refresh")
    public String refresh() {
        return "Echo Local ";
    }
}

@RestController
class ClientRestController {

    @Autowired
    private DiscoveryClientExample discoveryClientExample;

    @Autowired
    private FeignExample feignExample;

    @Autowired
    private RestTemplateExample restTemplateExample;

    @HystrixCommand(fallbackMethod = "fallback", groupKey = "Client", commandKey = "getClients", threadPoolKey = "clientThread")
    @GetMapping("/clients")
    public Object getClients() {
        Map<String, String> clients = new HashMap<String, String>(3);
        clients.put("DiscoveryClientExample Test", discoveryClientExample.serviceUrl());
        clients.put("FeignExample Test", feignExample.service());
        clients.put("RestTemplateExample Test", restTemplateExample.service());
        return clients;
    }

    public String fallback(Throwable hystrixCommand) {
        return "Fall Back clients: " + hystrixCommand.getMessage();
    }
}
